'use strict';

const BaseService = require('./base');
const {ca} = require("tencentcloud-sdk-nodejs/tencentcloud");
const modelName = 'Product';

class SchoolService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }
  getListOrder() {
    return [
      [
        'sort',
        'ASC'
      ]
    ]
  }
  getPageOrder() {
    return [
      [
        'sort',
        'ASC'
      ]
    ]
  }
  getInclude() {
    return [
      {
        model: this.ctx.model.Category,
        as: 'category'
      }
    ]
  }
  async create(data) {
    const res = await super.create(data);
    try {
      // 往图片库 添加图片
      await this.ctx.service.tiia.createImage({
        fileName: data.name,
        url: data.post_url,
        entityId: res.id
      });
    } catch (e) {
      console.log(e)
      // 回滚创建的商品
      await this.ctx.model[modelName].destroy({
        where: {
          id: res.id
        }
      })
      throw new Error(e)
    }
    return res
  }

  async update(id, data) {
    // 判断图片是否存在更新
    let findOne = await this.findOne(id);
    const res = await super.update(id, data);
    if (findOne.post_url !== data.post_url) {
      try {
        await this.ctx.service.tiia.deleteImage({
          fileName: findOne.name,
          entityId: findOne.id
        })
      } catch (e) {
        console.log(e)
      }
      // 往图片库 添加图片
      await this.ctx.service.tiia.createImage({
        entityId: findOne.id,
        fileName: data.name,
        url: data.post_url
      });
    }
    return res
  }

  async deleteById(id) {
    let findOne = await this.findOne(id);
    if (!findOne) {
      throw new Error('不存在');
    }
    this.ctx.service.tiia.deleteImage({
      fileName: findOne.name,
      entityId: findOne.id
    })
    return await super.deleteById(id);
  }
}

module.exports = SchoolService;
